const db = require('../../lib/conn_oracle')
const exists = require('../../util/exists')

//查询权限组信息
exports.getAuthoritysInfo = (req,res)=>{
    let authoritySql = `select * from c##wxw.vue_xfjcauthoritys order by id`
    let datas
    async function fun(){
        let authoritys = await db.search2(authoritySql)
        datas = {authoritys}
        res.json({
            status:1,
            msg:"查询成功",
            datas
        })
    }
    fun()
}

//查询已有权限
exports.hasDirs = (req,res)=>{
    // console.log(req.query);
    let {id} = req.query
    id = Number(id)
    // console.log(id);
    let hasDirsSql = `select *
                      from c##wxw.vue_xfjcauthority_dirs_middle
                      where authorityid = ${id}
                      order by authorityid,dirid
                     `
    let datas 
    async function fun(){
        let hasDirs = await db.search2(hasDirsSql)
        datas = {hasDirs}
        res.json({
            status:1,
            msg:"查询成功",
            datas
        })
    }
    fun()
}

//更新、新增、删除权限组
exports.editAuthoritys = async (req,res)=>{
    let {submitType,submitForm} = req.body
    let {ID,AUTHORITYNAME,REMARK} = submitForm
    // console.log(submitType);
    // console.log(submitForm);
    let resDatas
    let handleSql
    let handleData
    let msg
    let submitTypeStr
    let status
    /**
     * 数据库处理函数
     * @param {String} sql  sql语句
     * @param {Array} data  参数（以数组形式传递，批量处理使用嵌套数组）
     */
    const cudFun = async (sql,data)=>{
        let newAuthoritys = await db.writeTab(sql,data)
        resDatas = {newAuthoritys}
        msg = resDatas.newAuthoritys.errorNum ? `${submitTypeStr}失败，错误代码：ORA-` + resDatas.newAuthoritys : `${submitTypeStr}成功`
        status = 1
        return {
            status,
            msg,
            resDatas
        } 
    }

    if(submitType === "update"){
        submitTypeStr = "更新"
        handleData = [AUTHORITYNAME,REMARK,ID]
        handleSql = `
                     update c##wxw.vue_xfjcauthoritys
                     set
                     authorityname = :AUTHORITYNAME,
                     remark = :REMARK
                     where id = :ID
                    `
        let newAuthoritys = await cudFun(handleSql,handleData)
        res.json(newAuthoritys)
    }
    if(submitType === "add"){
        submitTypeStr = "新增"
        handleData = [AUTHORITYNAME,REMARK]
        handleSql = `
                     insert into c##wxw.vue_xfjcauthoritys(id,authorityname,remark)
                     values('',:AUTHORITYNAME,:REMARK)
                    `
        let newAuthoritys = await cudFun(handleSql,handleData)
        res.json(newAuthoritys)
    }
    if(submitType === "delete"){
        submitTypeStr = "删除"
        handleData = [ID]
        handleSql = `delete c##wxw.vue_xfjcauthoritys where id = :ID`
        let newAuthoritys = await cudFun(handleSql,handleData)
        if(newAuthoritys.msg.includes("失败")){
            newAuthoritys.msg = "权限组删除失败"
            res.json(newAuthoritys)
        }else{
            handleSql = `delete c##wxw.vue_xfjcauthority_dirs_middle where authorityid = :ID`
            let newAuthoritys = await cudFun(handleSql,handleData)
            if(newAuthoritys.msg.includes("失败")){
                newAuthoritys.msg = "目录所在权限组删除失败"
                res.json(newAuthoritys)
            }else{
                handleSql = `delete c##wxw.vue_xfjcrole_authority_middle where authorityid = :ID`
                let newAuthoritys = await cudFun(handleSql,handleData)
                if(newAuthoritys.msg.includes("失败")){
                    newAuthoritys.msg = "角色所分配权限组删除失败"
                    res.json(newAuthoritys) 
                }else{
                    newAuthoritys.msg = "权限组删除成功"           
                    res.json(newAuthoritys)
                }
            }
        }       
    }     
}


//权限变更

exports.changeAuthority = async (req,res)=>{
    let {authorityId , submitForm} = req.body
    let {oldAuth , newAuth} = submitForm   
    let resDatas 
    let handleSql
    let handleData
    let msg
    let status
    let options = {
        autoCommit: true,
    }
    // console.log(authorityId);    
    // console.log(oldAuth);
    // console.log(newAuth);
     /**
     * 数据库批量处理前数据转换
     * @param {Array} arr 转换嵌套数组前的数组
     * @param {Number} authId 权限组ID
     */
    const dataHanding = (authId,arr)=>{
        let newArr = []
        for(let i = 0;i < arr.length;i++){           
            newArr.push([Number(authId),Number(arr[i])])          
        }
        // console.log(newArr)        
        return newArr
    }
    /**
     * 数据库处理
     * @param {String} changeType 修改类型：singleAdd(单个新增)、singleDel(单个权限删除)、AuthDel(同一权限组内所有权限均删除，变更后已无任何权限)、
     *                                     batchAdd(批量新增)、batchDel(批量删除)
     * @param {Array} data 数据，单个处理以数组形式传入、批量处理以嵌套数组形式传入
     * @param {Object} options ORACLE处理配置，批量处理时使用
     */
    const authChange = async (changeType,data,ops=options)=>{
        if(changeType === "AuthDel"){
            handleSql = `delete c##wxw.vue_xfjcauthority_dirs_middle where authorityid = :authorityId`
        }else{
            handleSql = changeType.includes("Add") ? `insert into c##wxw.vue_xfjcauthority_dirs_middle(id,authorityid,dirid) 
                                                      values('',:authorityId,:dirid)
                                                     `
                                                   : `delete c##wxw.vue_xfjcauthority_dirs_middle 
                                                      where authorityid = :authorityId
                                                        and dirid = :dirid
                                                     `
        }  
        let changeTypeStr = changeType.includes("Del") ? "删除" : "新增"
        let newAuthoritys = (changeType.includes("single") ||  changeType === "AuthDel") ? await db.writeTab(handleSql,data) : await db.writeManyTab2(handleSql,data,ops)                        
        resDatas = {newAuthoritys}            
        msg = (resDatas.newAuthoritys.errorNum || resDatas.newAuthoritys.code ) ? `${changeTypeStr}权限失败，错误代码：ORA-` + resDatas.newAuthoritys  
                                                                                : `${changeTypeStr}权限成功`
        status = (resDatas.newAuthoritys.errorNum || resDatas.newAuthoritys.code ) ? 0 : 1
        return {
            status,
            resDatas,
            msg
        }
    }

    if(!oldAuth && newAuth){
        handleData = dataHanding(authorityId,newAuth)            
        let newAuthoritys = await authChange("batchAdd",handleData) // msg = "原无权限，现新增" 
        res.json(newAuthoritys)
    }else if(oldAuth && !newAuth){
        handleData = [Number(authorityId)]     
        let newAuthoritys = await authChange("AuthDel",handleData) // msg = "原有权限，后无所有权限，删除" 
        res.json(newAuthoritys)
    }else{
    //    长度相同，也需要判断权限明细是否有不同    
       let needDel = exists.exists(oldAuth,newAuth) //须删除
       let needAdd = exists.exists(newAuth,oldAuth) //须增加
       let ctStr 
    //    console.log(needDel);
    //    console.log(needAdd);       
       if(!needDel.length && !needAdd.length){
            msg = "权限未作修改"           
            status = 0
            res.json({
                status,
                msg
           })
       }else if((needDel.length && !needAdd.length) || (!needDel.length && needAdd.length)){
            if(needDel.length && !needAdd.length && needDel.length > 1){
                ctStr = "batchDel"
                handleData = dataHanding(authorityId,needDel) 
            }else if(needDel.length && !needAdd.length && needDel.length === 1){
                ctStr = "singleDel"
                handleData = [Number(authorityId),Number(needDel[0])]
            }else if(!needDel.length && needAdd.length && needAdd.length > 1){
                ctStr = "batchAdd"
                handleData = dataHanding(authorityId,needAdd) 
            }else if(!needDel.length && needAdd.length && needAdd.length === 1){
                ctStr = "singleAdd"
                handleData = [Number(authorityId),Number(needAdd[0])]
            } 
            let newAuthoritysDel = await authChange(ctStr,handleData)
            if(newAuthoritysDel.msg.includes("失败")){
                msg = "权限修改失败"           
                status = 0
                res.json({
                    status,
                    msg
                })
            }else{
                msg = "权限修改成功"           
                status = 1
                res.json({
                    status,
                    msg
                })
            }
       }else{
            //需要缩减和增加权限(先增加，后删除)
            ctStr = needAdd.length > 1 ? "batchAdd" : "singleAdd"
            handleData = needAdd.length > 1 ? dataHanding(authorityId,needAdd) : [Number(authorityId),Number(needAdd[0])]
            let newAuthoritysAdd = await authChange(ctStr,handleData)
            if(newAuthoritysAdd.msg.includes("失败")){
                msg = "权限修改失败"           
                status = 0
                res.json({
                    status,
                    msg
                })
            }else{
                ctStr = needDel.length > 1 ? "batchDel" : "singleDel"
                handleData = needDel.length > 1 ? dataHanding(authorityId,needDel) : [Number(authorityId),Number(needDel[0])]
                let newAuthoritysDel = await authChange(ctStr,handleData)
                if(newAuthoritysDel.msg.includes("失败")){
                    msg = "权限修改失败"           
                    status = 0
                    res.json({
                        status,
                        msg
                    })
                }else{
                    msg = "权限修改成功"           
                    status = 1
                    res.json({
                        status,
                        msg
                    })
                }
            }
       }       
    }  
    
}

//获取目录及中间表信息
exports.getDirsAndMidInfo = async (req,res)=>{
    console.log(req.body)    
    let {id} = req.body
    // id = Number(id)  
    let dirsAndMidSql = `select d.*
                            ,adm.id as admid,adm.authorityid,adm.is_add,adm.is_update,adm.is_del
                        from c##wxw.vue_xfjcDirs d
                        left join c##wxw.vue_xfjcauthority_dirs_middle adm
                        on adm.dirid = d.id
                        and authorityid = :id
                        order by d.dirlevel
                        `
    let resDatas
    let status
    let msg
    try{
        let dirsAndMid = await db.search(dirsAndMidSql,[id])
        resDatas = {dirsAndMid}
        msg = "查询成功"
        status = 1
        res.json({
            status,
            msg,
            resDatas
        })
    }catch(err){
        console.log(err)
        msg = "查询失败"
        status = 0 
        res.json({
            status,
            msg,
            resDatas 
        })
    }                    
}